from PySide6.QtGui import QAction
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit
from PySide6.QtCore import Qt
import sys

"""
    对【窗体】进行上下文菜单添加 >>> 1.x
    对【控件】进行上下文菜单添加 >>> 2.x
"""
class MyWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()

        self.lineEdit1 = QLineEdit()
        self.lineEdit1.setPlaceholderText('右键自定义控件上下文菜单')
        # DOC: 2.1 设置控件的上下文菜单
        self.lineEdit1.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
        # DOC: 2.2 Action创建 & 添加Action到上下文菜单
        self.sendValAction = QAction('发送值到lineEdit2')
        self.cleanValAction = QAction('清空')
        self.lineEdit1.addActions([self.sendValAction, self.cleanValAction])

        self.lineEdit2 = QLineEdit()
        self.lineEdit2.setPlaceholderText('右键原有的控件上下文菜单')

        # DOC: 1.1 设置窗体的上下文策略
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)

        # DOC: 1.2 Action创建 & 添加Action到上下文菜单
        self.openFileAction = QAction('打开文件')
        self.closeFileAction = QAction('关闭文件')
        self.addActions([self.openFileAction, self.closeFileAction])



        self.layout = QVBoxLayout()
        self.layout.addWidget(self.lineEdit1)
        self.layout.addWidget(self.lineEdit2)
        self.setLayout(self.layout)

        self.bind()

    def bind(self):
        # DOC: 1.3 给添加的Action绑定逻辑
        self.openFileAction.triggered.connect(lambda: print('打开文件'))
        self.closeFileAction.triggered.connect(lambda: print('关闭文件'))

        # DOC: 2.3 给添加的Action绑定逻辑
        self.sendValAction.triggered.connect(lambda: self.lineEdit2.setText(self.lineEdit1.text()))
        self.cleanValAction.triggered.connect(lambda: self.lineEdit1.clear())



if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    app.exec()